//
//  main.m
//  xsd2cocoa
//
//  Created by Stefan Winter on 5/21/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "XSDschema.h"

NSManagedObjectModel *managedObjectModel();
NSManagedObjectContext *managedObjectContext();
BOOL hasOneMoreArgument(int argc, int currentPos);

int main (int argc, const char * argv[])
{
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    // Create the managed object context
    //        NSManagedObjectContext *context = managedObjectContext();
    
    NSFileManager* fm = [NSFileManager defaultManager];
    
    if(argc == 1) {
        NSLog(@"\nVersion: 0.1\nUse: xsd2cococa [-out FOLDER] XSDFILE");
        exit(1);
    }
    
    NSMutableDictionary* options = [NSMutableDictionary dictionary];
    for(int i=0; i<argc; i++) {
        NSString* anArg = [NSString stringWithCString: argv[i] encoding: NSUTF8StringEncoding];
        if([anArg hasPrefix: @"-"]) {
            if([anArg isEqual: @"-out"] && hasOneMoreArgument(argc, i)) {
                [options setObject: [NSString stringWithCString: argv[i + 1] encoding: NSUTF8StringEncoding] forKey: anArg];
            } else {
                NSLog(@"\nUnknown or wrong argument %@, nothing will be generated", anArg);
                exit(1);
            }
        }
    }
    
    NSURL *schemaURL = [NSURL fileURLWithPath: [NSString stringWithCString: argv[argc - 1] encoding: NSUTF8StringEncoding]];
    if(![fm isReadableFileAtPath: [schemaURL path]]) {
        NSLog(@"Schema at %@ cannot be found", [schemaURL path]);
        exit(1);
    }
    
    NSError* error = nil;
    XSDschema* schema = [XSDschema newWithUrl: schemaURL prefix: nil error: &error];
    
    if( error == nil) {
        NSString *path = [[[NSProcessInfo processInfo] arguments] objectAtIndex:0];
        NSURL* executableUrl = [NSURL fileURLWithPath: [path stringByDeletingPathExtension] isDirectory: YES];
        NSURL* folderUrl = [executableUrl URLByDeletingLastPathComponent];
        NSURL *templateUrl = [folderUrl URLByAppendingPathComponent:@"standard-template.xml"];
        
        [schema loadTemplate: templateUrl error: &error];
    
        if(error == nil) {        
            NSURL* outFolder = [NSURL fileURLWithPath: [fm currentDirectoryPath]];
            if([options objectForKey: @"-out"] != nil) {
                outFolder = [NSURL fileURLWithPath: [options objectForKey:@"-out"]];
            }
            
            //    
            [schema generateInto: outFolder error: &error];
        }
    }
    if(error != nil) {
        NSLog(@"Error while saving %@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
    }
    //        // Save the managed object context
    //        NSError *error = nil;    
    //        if (![context save:&error]) {
    //            NSLog(@"Error while saving %@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
    //            [pool drain]; 
    //            exit(1);
    //        }
    [pool drain];
    return 0;
}

NSManagedObjectModel *managedObjectModel() {
    
    static NSManagedObjectModel *model = nil;
    
    if (model != nil) {
        return model;
    }
    
    NSString *path = [[[NSProcessInfo processInfo] arguments] objectAtIndex:0];
    path = [path stringByDeletingPathExtension];
    NSURL *modelURL = [NSURL fileURLWithPath:[path stringByAppendingPathExtension:@"momd"]];
    model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    
    return model;
}

NSManagedObjectContext *managedObjectContext() {
    
    static NSManagedObjectContext *context = nil;
    if (context != nil) {
        return context;
    }
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];        
    context = [[NSManagedObjectContext alloc] init];
    
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: managedObjectModel()];
    [context setPersistentStoreCoordinator: coordinator];
    
    NSString *STORE_TYPE = NSSQLiteStoreType;
    
    NSString *path = [[[NSProcessInfo processInfo] arguments] objectAtIndex:0];
    path = [path stringByDeletingPathExtension];
    NSURL *url = [NSURL fileURLWithPath:[path stringByAppendingPathExtension:@"sqlite"]];
    
    NSError *error;
    NSPersistentStore *newStore = [coordinator addPersistentStoreWithType:STORE_TYPE configuration:nil URL:url options:nil error:&error];
    
    if (newStore == nil) {
        NSLog(@"Store Configuration Failure %@",
              ([error localizedDescription] != nil) ?
              [error localizedDescription] : @"Unknown Error");
    }
    [pool drain];
    return context;
}

BOOL hasOneMoreArgument(int argc, int currentPos) {
    return argc > (currentPos + 1);
}

